import { getCartInfo, getCurrentUser, newOrder } from '@/services/ant-design-pro/api';
import {
  ModalForm,
  PageContainer,
  ProForm,
  ProFormText,
  StepsForm,
} from '@ant-design/pro-components';
import type { CheckboxProps } from 'antd';
import { Button, Card, Checkbox, Image, message } from 'antd';
import React, { useEffect, useState } from 'react';
import './index.less';

const Cart: React.FC = () => {
  //获取用户购物车

  const [cartState, setCartState] = useState<API.CartInfo>({});
  const getCart = async () => {
    try {
      const msg = await getCartInfo();
      if (msg.data) {
        setCartState(msg);
      }
    } catch (error) {
      console.log(error);
    }
  };
  useEffect(() => {
    getCart().then();
  }, []);

  //获取当前用户
  const [currentUser, setCurrentUser] = useState<API.CurrentUser>({});
  const getUser = async () => {
    try {
      const msg = await getCurrentUser();
      if (msg.data) {
        setCurrentUser(msg);
      }
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    getUser().then();
  }, []);

  //计算总价
  const [totalPrice, setTotalPrice] = useState(0);

  //获取用户的商品选择
  const [selectItemState, setSelectItemState] = useState<{ itemId: string; quantity: number }[]>(
    [],
  );
  const calculateTotal = () => {
    if (cartState.data) {
      for (let selection of selectItemState) {
        for (let cartItem of cartState.data) {
          if (selection.itemId === cartItem.itemId) {
            setTotalPrice(cartItem.totalPrice);
            break;
          }
        }
      }
    }
  };
  const [counter, setCounter] = useState(0);
  const handleSelectChange = (e: any) => {
    const itemId: string = e.target.dataset.id;
    const quantity: number = e.target.dataset.quantity;
    const itemList = selectItemState;
    if (itemList) {
      if (e.target.checked) {
        itemList.push({ itemId, quantity });
        setCounter(counter + 1);
      } else {
        for (let selection of itemList)
          if (selection.itemId === itemId) {
            itemList.splice(itemList.indexOf(selection), 1);
            setCounter(counter - 1);
            break;
          }
      }
      setSelectItemState(itemList);
    }
  };

  //当用户修改商品数量时
  const onQuantityChange = (e: any) => {
    console.log(e.target.name, e.target.value);
  };

  //模态新建订单框
  const Components = {
    ProForm,
    ModalForm,
    StepsForm,
  };
  const [type] = useState<keyof typeof Components>('ModalForm');
  const FormComponents = Components[type as 'ModalForm'];
  const handleSubmit = async (values: API.NewOrderParams) => {
    //添加数据
    values.orderLines = selectItemState;
    values.exprDate = new Date().toDateString();
    calculateTotal();
    values.totalPrice = totalPrice;

    // 校验
    try {
      // 注册
      const msg = await newOrder({
        ...values,
      });
      if (!msg.data) {
        message.error(msg.message);
        return;
      } else {
        message.success('下单成功');
      }
    } catch (error) {
      const defaultLoginFailureMessage = '下单失败，请重试！';
      console.log(error);
      message.error(defaultLoginFailureMessage);
    }
  };
  //获取用户是否使用了ship地址
  const [choice, setChoice] = useState(false);
  const makeChoice: CheckboxProps['onChange'] = () => {
    setChoice(!choice);
  };

  return (
    <>
      <PageContainer>
        {counter > 0 && (
          <div className="messageDiv">
            <b>您已选择{counter}件商品</b>
            <div>
              <FormComponents
                // @ts-ignore
                labelWidth="auto"
                title="新建订单"
                trigger={<Button type="primary">购买</Button>}
                onFinish={async (values: any) => {
                  await handleSubmit(values as API.NewOrderParams);
                  console.log(values);
                }}
                initialValues={{}}
              >
                <ProForm.Group>
                  <ProFormText
                    width="md"
                    name="billAddr1"
                    label="账单地址1"
                    tooltip="最长为 24 位"
                    placeholder="请输入地址"
                    initialValue={currentUser.data?.addr1}
                    rules={[
                      {
                        required: true,
                        message: '地址1是必填项！',
                      },
                    ]}
                  />
                  <ProFormText
                    width="md"
                    name="billAddr2"
                    label="账单地址2"
                    placeholder="请输入地址"
                  />
                </ProForm.Group>
                <ProForm.Group>
                  <ProFormText
                    name="billCity"
                    width="md"
                    label="居住城市"
                    placeholder="请输入城市"
                    initialValue={currentUser.data?.city}
                    rules={[
                      {
                        required: true,
                        message: '城市是必填项！',
                      },
                    ]}
                  />
                  <ProFormText
                    name="billState"
                    width="md"
                    label="居住洲"
                    placeholder="请输入洲"
                    initialValue={currentUser.data?.state}
                    rules={[
                      {
                        required: true,
                        message: '居住洲是必填项！',
                      },
                    ]}
                  />
                  <ProFormText
                    name="billZip"
                    width="md"
                    label="Zip"
                    placeholder="请输入Zip"
                    initialValue={currentUser.data?.zip}
                    rules={[
                      {
                        required: true,
                        message: 'Zip是必填项！',
                      },
                    ]}
                  />
                  <ProFormText
                    name="billCountry"
                    width="md"
                    label="Country"
                    placeholder="请输入国家"
                    initialValue={currentUser.data?.country}
                    rules={[
                      {
                        required: true,
                        message: 'Zip是必填项！',
                      },
                    ]}
                  />
                </ProForm.Group>
                <ProForm.Group>
                  <ProFormText
                    name="billToFirstname"
                    width="md"
                    label="FirstName"
                    placeholder="请输入firstName"
                    initialValue={currentUser.data?.firstname}
                    rules={[
                      {
                        required: true,
                        message: 'firstName是必填项！',
                      },
                    ]}
                  />
                  <ProFormText
                    name="billToLastname"
                    width="md"
                    label="LirstName"
                    placeholder="请输入lastName"
                    initialValue={currentUser.data?.lastname}
                    rules={[
                      {
                        required: true,
                        message: 'lastName是必填项！',
                      },
                    ]}
                  />
                </ProForm.Group>
                <Checkbox onChange={makeChoice}>填写ship账单</Checkbox>
                {choice && (
                  <div>
                    <ProForm.Group>
                      <ProFormText
                        width="md"
                        name="shipAddr1"
                        label="账单地址1"
                        tooltip="最长为 24 位"
                        placeholder="请输入地址"
                        initialValue={currentUser.data?.addr1}
                        rules={[
                          {
                            required: true,
                            message: '地址1是必填项！',
                          },
                        ]}
                      />
                      <ProFormText
                        width="md"
                        name="shipAddr2"
                        label="账单地址2"
                        placeholder="请输入地址"
                      />
                    </ProForm.Group>
                    <ProForm.Group>
                      <ProFormText
                        name="shipCity"
                        width="md"
                        label="居住城市"
                        placeholder="请输入城市"
                        initialValue={currentUser.data?.city}
                      />
                      <ProFormText
                        name="shipState"
                        width="md"
                        label="居住洲"
                        placeholder="请输入洲"
                        initialValue={currentUser.data?.state}
                      />
                      <ProFormText
                        name="shipCountry"
                        width="md"
                        label="Country"
                        placeholder="请输入国家"
                        initialValue={currentUser.data?.country}
                        rules={[
                          {
                            required: true,
                            message: 'Zip是必填项！',
                          },
                        ]}
                      />
                      <ProFormText
                        name="shipZip"
                        width="md"
                        label="Zip"
                        placeholder="请输入Zip"
                        initialValue={currentUser.data?.zip}
                      />
                    </ProForm.Group>
                    <ProForm.Group>
                      <ProFormText
                        name="shipToFirstname"
                        width="md"
                        label="FirstName"
                        placeholder="请输入firstName"
                        initialValue={currentUser.data?.firstname}
                      />
                      <ProFormText
                        name="shipToLastname"
                        width="md"
                        label="LirstName"
                        placeholder="请输入lastName"
                        initialValue={currentUser.data?.lastname}
                      />
                    </ProForm.Group>
                  </div>
                )}
                <ProForm.Group>
                  <ProFormText
                    name="cardType"
                    width="md"
                    label="cardType"
                    placeholder="请输入信用卡类型"
                    initialValue={'X'}
                    rules={[
                      {
                        required: true,
                        message: 'cardType是必填项！',
                      },
                    ]}
                  />
                  <ProFormText
                    name="creditCard"
                    width="md"
                    label="信用卡号"
                    placeholder="请输入假数据"
                    initialValue={'123456789'}
                    rules={[
                      {
                        required: true,
                        message: '信用卡号是必填项！',
                      },
                    ]}
                  />
                </ProForm.Group>
                <ProForm.Group>
                  <ProFormText
                    name="courier"
                    width="md"
                    label="courier"
                    placeholder="请输入courier"
                    initialValue={'xxxxxxxxxxxxxxxxxx'}
                    rules={[
                      {
                        required: true,
                        message: 'courier是必填项！',
                      },
                    ]}
                  />
                  <ProFormText
                    name="locale"
                    width="md"
                    label="locale"
                    placeholder="请输入locale"
                    initialValue={currentUser.data?.addr1}
                    rules={[
                      {
                        required: true,
                        message: 'locale是必填项！',
                      },
                    ]}
                  />
                </ProForm.Group>
              </FormComponents>
            </div>
          </div>
        )}
        {cartState.data &&
          cartState.data.length > 0 &&
          cartState.data.map((cartItem) => (
            <Card className="cartCard" key={cartItem.itemId} title={cartItem.name}>
              <input
                type="checkbox"
                className="selectBox"
                data-id={cartItem.itemId}
                data-quantity={cartItem.quantity}
                onChange={handleSelectChange}
              />
              <div className="pet-img">
                <Image className="img" src={cartItem.imgUrl} />
              </div>
              <div className="content">
                <b>商品名：</b>
                <p className="">{cartItem.name}</p>
                <b>供应商：</b>
                <p className="">{cartItem.supplierName}</p>
                <b>商品描述：</b>
                <p className="">{cartItem.desc}</p>
              </div>
              <div className="dataField">
                <div className="quantity">
                  <b>数量：</b>
                  <input
                    type="number"
                    min={1}
                    max={100}
                    name={cartItem.itemId}
                    defaultValue={cartItem.quantity}
                    onChange={onQuantityChange}
                  />
                </div>
                <div className="totalPrice">
                  <b>总价：</b>
                  <p className="">{cartItem.totalPrice}</p>
                </div>
              </div>
              <div className="buttonGroup">
                <Button type="primary" ghost>
                  查看商品
                </Button>
                <br />
                <Button type="primary">删除</Button>
              </div>
            </Card>
          ))}

        {!cartState.data && (
          <div className="messageDiv">
            <b>您的购物车为空</b>
          </div>
        )}
      </PageContainer>
    </>
  );
};

export default Cart;
